package com.ukao.cashregister.ui.vipManager;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.VipGroupListAdapter;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.VipGroupBean;
import com.ukao.cashregister.bean.VipLeverBean;
import com.ukao.cashregister.dialog.BuildGroupDialogFragment;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.listener.MyTextWatcher;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.pesenter.VipManagerPesenter;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.VipManagerView;
import com.ukao.cashregister.widget.DividerDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.build_vip;


/**
 * 组员管理
 */
public class VipManagerFragment extends MvpFragment<VipManagerPesenter> implements VipManagerView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final int ADD_VIP = build_vip;
    @BindView(R.id.fragment_arrive_shop_search1_edit)
    EditText fragmentArriveShopSearch1Edit;
    @BindView(R.id.search_button)
    Button searchButton;
    @BindView(build_vip)
    Button buildVip;
    @BindView(R.id.group_recycler_view)
    RecyclerView groupRecyclerView;
    @BindView(R.id.build_grouping)
    Button buildGrouping;
    Unbinder unbinder;





    private VipGroupListAdapter mVipGroupListAdapter;
    private FragmentTransaction fragmentTransaction;
    private int mCurrentPosition;

    private FragmentManager fragmentManager;
    private ArrayList<VipLeverBean.ListBean> mvipleverBean;
    private ArrayList<VipGroupBean> mvipGroupBean;
    private Fragment mFragment;
    private VipGroupBean mvipGroupBeans;
    private int VipGroupPos;


    public static VipManagerFragment newInstance(  ) {
        VipManagerFragment fragment = new VipManagerFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {


        }
    }

    @Override
    protected VipManagerPesenter createPresenter() {
        return new VipManagerPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_vip_manager, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();

        return view;


    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mvpPresenter.allSserGroup(_mActivity);
    }

    @Override
    protected void initView() {
        fragmentArriveShopSearch1Edit.setText("");
        mvipleverBean=new ArrayList<>();
        mvipGroupBean=new ArrayList<>();
        if (!CheckUtils.isNull(fragmentArriveShopSearch1Edit)){  fragmentArriveShopSearch1Edit.setText("");}
        initLinearRecyclerView(groupRecyclerView);
        mVipGroupListAdapter = new VipGroupListAdapter(activity, mvipGroupBean,true);
        groupRecyclerView.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
        groupRecyclerView.setAdapter(mVipGroupListAdapter);





    }

    @Override
    protected void initListener() {
        super.initListener();
        mVipGroupListAdapter.setOnItemClickListener(mOnItemClickListener);
        fragmentArriveShopSearch1Edit.addTextChangedListener(mTextWatcher);
        fragmentArriveShopSearch1Edit.setOnEditorActionListener(mOnEditorActionListener);

    }


    private TextView.OnEditorActionListener mOnEditorActionListener=new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                     if (actionId== KeyEvent.KEYCODE_ENTER) {
                         searchVipUse();
                     }
            return false;
        }
    };


    TextWatcher mTextWatcher=new MyTextWatcher(){

        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            try {

                if (!CheckUtils.isNull(mFragment)){
                    VipTableFragment currentFragment = (VipTableFragment)mFragment;
                    currentFragment.setnullSearchValue(s.toString());

                }
            }catch (Exception e){

            }

        }
    };





    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {


        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            VipGroupBean item = (VipGroupBean) o;
            showSelectGroup(i, item);
        }


    };
    private void showSelectGroup(int i, VipGroupBean item) {
        if (!item.isCheck()) {
            controlShowFragment(i);
            item.setCheck(!item.isCheck());
            List<VipGroupBean> mData = mVipGroupListAdapter.getDatas();
            for (int j = 0; j < mData.size(); j++) {
                if (i != j) {
                    mData.get(j).setCheck(false);

                }
            }

            mVipGroupListAdapter.notifyDataSetChanged();
        }
    }

    private void controlShowFragment(int position) {
         fragmentManager= getChildFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();

        Fragment oldFragment = fragmentManager.findFragmentByTag(makeTag(mCurrentPosition));
        if (oldFragment != null) {
            fragmentTransaction.hide(oldFragment);
        }
        mCurrentPosition = position;

        Fragment currentFragment = fragmentManager.findFragmentByTag(makeTag(position));
        if (currentFragment != null) {
            fragmentTransaction.show(currentFragment);
        } else {

            addFragment(position);
        }
        fragmentTransaction.commitAllowingStateLoss();


    }


    private String makeTag(int position) {
        return R.id.frament_layout + "" + position;
    }

    private void addFragment(int position) {

        List<VipGroupBean> mDatas = mVipGroupListAdapter.getDatas();
        fragmentTransaction.add(R.id.frament_layout, VipTableFragment.newInstance(mDatas.get(position).getId(), mvipleverBean), makeTag(position));


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }



    @OnClick({R.id.search_button, build_vip, R.id.build_grouping})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_button:

                searchVipUse();


                break;
            case build_vip:
                ArrayList<VipGroupBean> mVipGroupData =(  ArrayList<VipGroupBean>)mVipGroupListAdapter.getDatas();
                if (!CheckUtils.isEmpty(mVipGroupData)&&!CheckUtils.isEmpty(mVipGroupListAdapter.getDatas())){
                    List<VipGroupBean> datas = mVipGroupListAdapter.getDatas();
                     VipGroupPos= 0;
                    for (int i = 0; i < datas.size(); i++) {
                        VipGroupBean vipGroupBean = datas.get(i);
                        if (vipGroupBean.isCheck()) {
                            VipGroupPos=i;
                            mvipGroupBeans = vipGroupBean;
                        }
                    }

                    startForResult(CreateVipFragment.newInstance(mVipGroupData,mvipleverBean), ADD_VIP);
                }




                break;
            case R.id.build_grouping:
                BuildGroupDialogFragment mBuildGroup = new BuildGroupDialogFragment();
                Bundle bundle = new Bundle();
                mBuildGroup.setArguments(bundle);
                mBuildGroup.setOnSureClickListener(mBuildgroupingListener);
                mBuildGroup.show(getChildFragmentManager(), "buildgrouping");



                break;


        }
    }

    private void searchVipUse() {
        if (CheckUtils.isNull(fragmentManager))return;
        mFragment=fragmentManager.findFragmentByTag(makeTag(0));
        if (!CheckUtils.isNull(mFragment)){
         VipTableFragment currentFragment = (VipTableFragment)mFragment;
            String  strname=getText(fragmentArriveShopSearch1Edit);
            currentFragment.setSearchValue(strname);
            showSelectGroup(0, mVipGroupListAdapter.getItem(0));

        }
    }

    @Override
    protected boolean useEventBus() {
        return super.useEventBus();
    }



    private OnDialogSureClickListener mBuildgroupingListener=new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            String  str=(String)message;
                mvpPresenter.buildGrouping(_mActivity,str);
        }
    };

    @Override
    protected void onFragmentResult(int requestCode, int resultCode, Bundle data) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ADD_VIP:
                    mvipGroupBean.get(VipGroupPos).setCheck(true);
                    for (int i = 0; i < mvipGroupBean.size(); i++) {
                        VipGroupBean item = mvipGroupBean.get(i);
                        if (VipGroupPos!=i){
                            item.setCheck(false);
                        }

                    }
                    mVipGroupListAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void loadvipGroupSucceed(  List<VipGroupBean> mvipGroupBeans) {

            if (!CheckUtils.isEmpty(mvipGroupBeans)){
                mvipGroupBean.addAll(mvipGroupBeans);


            }

             mvpPresenter.vipUserLever(_mActivity);


    }

    @Override
    public void loadFailure(String message) {
        T.show( message);

    }

    @Override
    public void loadvipLeverSucceed(List<VipLeverBean.ListBean> mvipleverBean) {
        if (!CheckUtils.isEmpty(mvipGroupBean))
        mvipGroupBean.get(0).setCheck(true);
        mVipGroupListAdapter.setDatas(mvipGroupBean);
        this.mvipleverBean= (ArrayList<VipLeverBean.ListBean>) mvipleverBean;
        controlShowFragment(0);
    }

    @Override
    public void buildGroupingSucceed(VipGroupBean mVipGroupBean ) {
        mVipGroupListAdapter.getDatas().add(mVipGroupBean);
        mVipGroupListAdapter.notifyDataSetChanged();

    }

    @Override
    public void loadAllSserGroupSucceed(List<VipGroupBean> allSserGroup) {
        mvipGroupBean.addAll(allSserGroup);
        mvpPresenter.vipUserGroupData(_mActivity);
    }



}